<?php
namespace app\home\controller;
use app\home\model\UserOrder;
/**
 * Created by PhpStorm.
 * User: zhangzhiyuan
 * Date: 2019/2/28 0028
 * Time: 9:54
 */
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use app\home\service\NotifyService;

include "static/alipay/aop/AopClient.php";
include "static/alipay/aop/request/AlipayTradeAppPayRequest.php";
class Alipay extends Controller
{
    /**
     * 支付宝统一下单
     * @ author: zhangzhiyuan
     * @ email: fh515934402@163.common
     * @ date: 2017/8/17 19:25
     */
    public function pay(Request $request)
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 
        set_cors();
        $param = $request->param();
        if(empty($param['userid']) || empty($param['stroeid'])){
            puterror(1);
        }
        if(empty($param['extra'])) {
            $param['extra'] = get_redis_value($param['userid']);
        }
        $orderModel = new UserOrder();
        $data =$orderModel->create_order_old($param['userid'],$param['channel'],$param['stroeid'],1,$param['extra']);
        $info=json_decode($data,true);
        $http_response_header=$this->alipay_pay_handle($info['subject'],$info['orderid'],$info['price']);

        // 判断是线上还是内网测试
        if(env('IS_DEVELOP') == 1){
            //发货
            $tradeLog = (new \app\home\model\TradeLog)->where(['id'=>$info['orderid']])->find();
            
            $notifyService = new NotifyService();
            
            if($notifyService->notifyProcess($tradeLog) == false){
                return false;
            }
            $arr['code']='success';
            $arr['data']=$http_response_header;
            $arr['total_amount'] = $info['price'];
            echo json_encode($arr);exit;
            
            // var_dump(123);die;
            // 对内网测试进行特殊处理 直接触发回调
            // $time= date('Y-m-d H:i:s',time());
            // try{
            //     $res =Db_connect_server_pay_domian($info['orderid'],$info['price'],$time);
            // }catch (\Error $exception){
            //     mylog('内网测试-error:'.$exception->getMessage().' line:'.$exception->getLine().' file:'.$exception->getFile());
            // }

            // if($res == 'success'){
            //     $arr['code']='success';
            //     $arr['data']=$http_response_header;
            //     $arr['total_amount'] = $info['price'];
            //     echo json_encode($arr);exit;
            // }
        }else{
            $arr['code']='success';
            $arr['order']=$info['orderid'];
            $arr['data']=$http_response_header;
            $arr['total_amount'] = $info['price'];
            echo json_encode($arr);exit;
        }

    }
    
    function alipay_pay_handle($subject,$order_id,$total_price){
        /*支付宝支付接口*/
        $aop = new \AopClient();
        //**沙箱测试支付宝开始
        $aop->gatewayUrl = config('alipay.gatewayUrl');
        //实际上线app id需真实的
        $aop->appId = config('alipay.appid'); //开发者appid
        $aop->rsaPrivateKey=config('alipay.rsaPrivateKey');
        $aop->format = "json";
        $aop->charset = "utf-8";
        $aop->signType = "RSA2";
        $aop->alipayrsaPublicKey = config('alipay.alipayrsaPublicKey');
        $bizcontent = json_encode([
            'subject'=>$subject,
            'out_trade_no'=>$order_id, //此订单号为商户唯一订单号
            'total_amount'=>$total_price, //保留两位小数
            'product_code'=>'QUICK_MSECURITY_PAY'
        ]);
        //**沙箱测试支付宝结束
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        $request = new \AlipayTradeAppPayRequest();
        //支付宝回调
        $request->setNotifyUrl(config('alipay.NotifyUrl'),true,true);
        $request->setBizContent($bizcontent);
        //这里和普通的接口调用不同，使用的是sdkExecute
        $response = $aop->sdkExecute($request);
        return $response;
    }

    public  function alipay_notify_result(){
        $aop = new \AopClient;
        $post = $_POST;
        $aop->alipayrsaPublicKey = config('alipay.alipayrsaPublicKey');
        $flag = $aop->rsaCheckV1($post, NULL, "RSA2");
        if($flag){
            if($post['trade_status'] == 'TRADE_SUCCESS' or $post['trade_status'] == 'TRADE_FINISHED'){
                //保存支付宝交易号
                if(!empty($post['trade_no'])){
                    $tradeLog = (new \app\home\model\TradeLog)->where(['id'=>$post['out_trade_no']])->find();
                    if ($tradeLog){
                        $tradeLog->transactionID = $post['trade_no'];
                        $tradeLog->save();
                    }
                }
                $res =Db_connect_server_pay_domian($post['out_trade_no'],$post['total_amount'],$post['gmt_payment']);
                if($res == 'success'){
                    echo 'success';
                }
            }
        }else{
            file_put_contents('orderalipay_error_log.txt', "订单".$post['out_trade_no']."支付失败\r\n", FILE_APPEND);
            echo "error";
        }
    }
}
